/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.risk.service.impl;


import com.koron.common.Tools;
import com.koron.common.bean.DepartmentTreeBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.web.Util;
import com.koron.hazardsource.util.BusinessCode;
import com.koron.risk.bean.CorpBean;
import com.koron.risk.bean.DeptSafetyStaff;
import com.koron.risk.bean.DeptSafetyStaffBean;
import com.koron.risk.domain.GridNode;
import com.koron.risk.mapper.GridNodeMapper;
import com.koron.risk.mapper.HazardSourceDistributeMapper;
import com.koron.risk.service.api.GridNodeService;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.swan.bean.MessageBean;

import java.text.NumberFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

@Service
public class GridNodeServiceImpl implements GridNodeService, ApplicationListener<ContextRefreshedEvent> {

    private final static Logger logger= LoggerFactory.getLogger(GridNodeServiceImpl.class);
    @Value("${app.orgCode}")
    private String orgCode;

    private String[] codeArray = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

    private ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();

    @Autowired
    private CorpManagementServiceImpl corpManagementService;

    @Autowired
    private Util util;

    private Map<String, String> positionMap = new ConcurrentHashMap();

    private Map<String, Map<String, List<String>>> childMap = new ConcurrentHashMap();

    private Map<String, List<Map>> corpNodesMap = new ConcurrentHashMap();
    private Map<String, Map> districtMap = new ConcurrentHashMap();

    private Map<String, Map> treeMap = new ConcurrentHashMap();

    private Map<String, List<String>> childCodeListMap = new ConcurrentHashMap();

    @SuppressWarnings("deprecation")
    @Override
    public MessageBean<?> save(StaffBean user, GridNode bean) {
        MessageBean<?> msg = MessageBean.create(0, "SUCCESS", void.class);
        if (StringUtils.isEmpty(bean.getName()) || StringUtils.isEmpty(bean.getCorpCode()) || StringUtils.isEmpty(bean.getPid())) {
            msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_SERVICE_EXCEPTION);
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            GridNodeMapper mapper = factory.getMapper(GridNodeMapper.class);
            GridNode parent = mapper.queryById(bean.getPid());
            if (parent != null) {
                //更新父级子节点数量
                Integer subnumber = parent.getSubnumber();
                subnumber++;
                parent.setSubnumber(subnumber);
                mapper.update(parent);
            }
            bean.setAddTime(new Date());
            bean.setAddUser(user.getCode());
            bean.setAddUserName(user.getName());
            bean.setId(DefaultIdGenerator.getInstance().generateLongId());
            bean.setCode(Tools.getCode32());
            bean.setStructureCode(generateCode(factory, bean));
            bean.setSubnumber(0);
            mapper.insert(bean);
            factory.close();
        } catch (Exception e) {
            msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
            factory.close(false);
            return msg;
        }

        singleThreadExecutor.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    List<String> idList = new ArrayList<>();
                    idList.add(bean.getId());
                    refReshChildMap2(bean.getPid(), idList, null);
                } catch (Exception e) {
                    logger.error(e.getMessage(),e);
                }
            }
        });

        return msg;
    }

    @SuppressWarnings({"deprecation"})
    @Override
    public Map<String, String> gridStaff(String code) {
        int type = 0;
        try (SessionFactory factory = new SessionFactory()) {
            GridNodeMapper mapper = factory.getMapper(GridNodeMapper.class);
            GridNode node = mapper.queryByCode(code);
            if (node == null) {
                type = 1;
            }
        }
        return queryStaff(code, type);
    }

    @SuppressWarnings({"unchecked", "deprecation", "rawtypes"})
    private Map<String, String> queryStaff(String id, int type) {
        Map<String, String> map = new HashMap<String, String>();
        try (SessionFactory factory = new SessionFactory()) {
            GridNodeMapper mapper = factory.getMapper(GridNodeMapper.class);
            GridNode node = mapper.queryByCode(id);
            if (node == null) { //部门
                MessageBean<?> msg = util.getParentDepts(id);
                if (msg.getCode() != 0) {
                    return null;
                }
                List<DepartmentTreeBean> list = null;
                if (msg.getData() == null) {
                    return null;
                }
                list = (List<DepartmentTreeBean>) msg.getData();
                if (list.isEmpty()) {
                    return null;
                }
                if (type == 1) {
                    list.remove(list.size() - 1);
                }
                ListIterator li = list.listIterator(list.size());
                while (li.hasPrevious()) {
                    DepartmentTreeBean bean = (DepartmentTreeBean) li.previous();
                    DeptSafetyStaff dss = mapper.queryDeptSafetyStaff(bean.getDepartmentCode());
                    if (dss != null) {
                        map.put("code", bean.getDepartmentCode());
                        map.put("businessStaffCode", dss.getBusinessStaffCode());
                        map.put("safetyStaffCode", dss.getSafetyStaffCode());
                        map.put("businessStaffName", dss.getBusinessStaffName());
                        map.put("safetyStaffName", dss.getSafetyStaffName());
                        map.put("safetyLeader", dss.getSafetyLeader());
                        map.put("safetyLeaderName", dss.getSafetyLeaderName());
                        map.put("safetyOfficer", dss.getSafetyOfficer());
                        map.put("safetyOfficerName", dss.getSafetyOfficerName());
                        return map;
                    }
                }
                return null;
            } else { //网格
                id = node.getPid();
                GridNode parent = mapper.queryById(id);
                if (parent == null) {
                    return queryStaff(id, type);
                } else {
                    if (!StringUtils.isEmpty(parent.getBusinessStaffCode()) || !StringUtils.isEmpty(parent.getSafetyStaffCode())) {
                        map.put("code", parent.getCode());
                        map.put("businessStaffCode", parent.getBusinessStaffCode());
                        map.put("safetyStaffCode", parent.getSafetyStaffCode());
                        map.put("businessStaffName", parent.getBusinessStaffName());
                        map.put("safetyStaffName", parent.getSafetyStaffName());
                        map.put("safetyLeader", parent.getSafetyLeader());
                        map.put("safetyLeaderName", parent.getSafetyLeaderName());
                        map.put("safetyOfficer", parent.getSafetyOfficer());
                        map.put("safetyOfficerName", parent.getSafetyOfficerName());
                        return map;
                    } else {
                        return queryStaff(parent.getCode(), type);
                    }
                }
            }
        } catch (Exception e) {
            return null;
        }
    }

    private String generateCode(SessionFactory factory, GridNode bean) {
        StringBuffer structureCode = new StringBuffer();
        GridNodeMapper mapper = factory.getMapper(GridNodeMapper.class);
        GridNode parent = mapper.queryById(bean.getPid());
        NumberFormat nf = NumberFormat.getInstance();
        nf.setGroupingUsed(false);
        nf.setMaximumIntegerDigits(2); // 设置最大整数位数
        nf.setMinimumIntegerDigits(2); // 设置最小整数位数
        Integer count = mapper.queryCountByPid(bean.getPid());
        if (parent == null) {
            if (count < 26) {
                structureCode.append("AA");
                structureCode.append(codeArray[count]);
            } else {
                count = count - 26;
                structureCode.append("AB");
                structureCode.append(codeArray[count]);
            }
            structureCode.append("01");
            return structureCode.toString();
        } else {
            structureCode.append(parent.getStructureCode());
        }
        structureCode.append(nf.format(count));
        return structureCode.toString();
    }

    @SuppressWarnings("deprecation")
    @Override
    public MessageBean<?> update(StaffBean user, GridNode bean) {
        MessageBean<?> msg = MessageBean.create(0, "SUCCESS", void.class);
        if (StringUtils.isEmpty(bean.getName()) || StringUtils.isEmpty(bean.getId())) {
            msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_SERVICE_EXCEPTION);
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            GridNodeMapper mapper = factory.getMapper(GridNodeMapper.class);
            bean.setUpdateTime(new Date());
            bean.setUpdateUser(user.getCode());
            bean.setUpdateUserName(user.getName());
            mapper.update(bean);
            factory.close();
        } catch (Exception e) {
            msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
            factory.close(false);
            return msg;
        }

        singleThreadExecutor.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    refReshChildMap(bean.getCorpCode());
                } catch (Exception e) {
                    logger.error(e.getMessage(),e);
                }
            }
        });

        return msg;
    }

    @SuppressWarnings({"resource", "deprecation"})
    @Override
    public MessageBean<?> delete(String id) {
        MessageBean<?> msg = MessageBean.create(0, "SUCCESS", void.class);
        if (StringUtils.isEmpty(id)) {
            msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_SERVICE_EXCEPTION);
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            GridNodeMapper mapper = factory.getMapper(GridNodeMapper.class);
            Integer count = mapper.subsetCount(id);
            if (count > 0) {
                msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
                msg.setDescription("存在下级节点,不能删除");
                factory.close();
                return msg;
            }
            GridNode bean = mapper.queryById(id);
            if (bean == null) {
                msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
                msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_SERVICE_EXCEPTION);
                return msg;
            }
            count = factory.getMapper(HazardSourceDistributeMapper.class).countByCorpAndGrid(bean.getCorpCode(), id);
            if (count > 0) {
                msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
                msg.setDescription("已关联危险源,不能删除");
                factory.close();
                return msg;
            }
            mapper.delete(id);
            GridNode parent = mapper.queryById(bean.getPid());
            List<GridNode> nodeList = mapper.queryByPid(bean.getPid());
            if (parent != null) {
                Integer subnumber = parent.getSubnumber();
                parent.setSubnumber(nodeList != null ? nodeList.size() : 0);
                mapper.update(parent);
            }
            refReshChildMap2(bean.getPid(), null, bean.getId());
            factory.close();
        } catch (Exception e) {
            msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
            factory.close(false);
            return msg;
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
        return msg;
    }

    @SuppressWarnings("deprecation")
    @Override
    public MessageBean<?> details(String id) {
        MessageBean<GridNode> msg = MessageBean.create(0, "SUCCESS", GridNode.class);
        if (StringUtils.isEmpty(id)) {
            msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_SERVICE_EXCEPTION);
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            GridNodeMapper mapper = factory.getMapper(GridNodeMapper.class);
            msg.setData(mapper.queryById(id));
            factory.close();
        } catch (Exception e) {
            msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
            factory.close();
            return msg;
        }
        return msg;
    }


    @SuppressWarnings("deprecation")
    @Override
    public MessageBean<?> setStaff(String deptCode, String safetyStaffCode, String safetyStaffName, String businessStaffCode, String businessStaffName,
                                   String safetyLeader, String safetyLeaderName, String safetyOfficer, String safetyOfficerName) {
        MessageBean<?> msg = MessageBean.create(0, "SUCCESS", void.class);
        SessionFactory factory = new SessionFactory();
        try {
            GridNodeMapper mapper = factory.getMapper(GridNodeMapper.class);
            Integer count = mapper.countDept(deptCode);
            if (count > 0) {//修改
                mapper.updateStaff(deptCode, safetyStaffCode, safetyStaffName, businessStaffCode, businessStaffName, safetyLeader, safetyLeaderName, safetyOfficer, safetyOfficerName);
            } else {//新增
                mapper.setStaff(deptCode, safetyStaffCode, safetyStaffName, businessStaffCode, businessStaffName, safetyLeader, safetyLeaderName, safetyOfficer, safetyOfficerName);
            }
            factory.close();
        } catch (Exception e) {
            msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
            factory.close(false);
            return msg;
        }
        return msg;
    }

    @SuppressWarnings({"deprecation", "rawtypes", "unchecked"})
    @Override
    public MessageBean<?> childList(String id, Integer recursive) {
        MessageBean<List> msg = MessageBean.create(0, "SUCCESS", List.class);
        try (SessionFactory factory = new SessionFactory()) {
            List<Map> list = getChildList(factory, id, recursive);
            if (list != null && list.size() > 0) {
                Integer subnumber = (Integer) list.get(0).get("subnumber");
                if (subnumber == 0) {
                    String corpCode = "776B361BFFAC4F00BBF459CD1303A8B2";
                    //获取指定code下的所有网格id集合(网格是id,部门是code)
                    Map<String, List<String>> map1 = childMap.get("776B361BFFAC4F00BBF459CD1303A8B2");
                    //获取父节点的下所有的子节点
                    List<String> idList = map1.get(id);
                    if (null != idList) {
                        if (recursive == 0 && (idList.size() > 1 || (idList.size() == 1 && !idList.get(0).equals(id)))) {
                            list.get(0).put("subnumber", idList.size());
                        }
                    }
                }
            }
            msg.setData(list);
        } catch (Exception e) {
            msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
            return msg;
        }
        return msg;
    }

    @Override
    public MessageBean<?> childList2(String corpCode, String id, Integer recursive) {
        MessageBean<List> msg = MessageBean.create(0, "SUCCESS", List.class);
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(corpCode)) {
                msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
                msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_SERVICE_EXCEPTION);
                return msg;
            }
            //判断corpCode是否为水司
            CorpBean bean = corpManagementService.getOne(corpCode).getData();
            if (null == bean) {
                msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
                msg.setDescription("不存在对应水司");
                return msg;
            }
            List<Map> list = new ArrayList<>();
            if (recursive == 0) {
                //查询不展开，即当前节点数据
                list = getChildList(factory, id, recursive);
            } else {
                if (null != districtMap && !districtMap.isEmpty()) {
                    Map<String, List<Map>> tempMap = districtMap.get(corpCode);
                    if (null != tempMap && !tempMap.isEmpty())
                        list = tempMap.get(id);
                }
                if (null == list || list.size() <= 0) {
                    list = getChildList(factory, id, recursive);
                }
            }
            msg.setData(list);
        } catch (Exception e) {
            msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
            return msg;
        }
        return msg;
    }

    private List<Map> getChildList(SessionFactory factory, String id, Integer recursive) {
        MessageBean<?> deptMsg = util.depttree(id, 0);
        List<Map> list = new ArrayList<Map>();
        GridNodeMapper mapper = factory.getMapper(GridNodeMapper.class);
        if (deptMsg.getData() != null) {
            List<DepartmentTreeBean> deptList = (List<DepartmentTreeBean>) deptMsg.getData();
            if (recursive == 0) {
                if (deptList.size() > 0) {
                    DepartmentTreeBean dept = deptList.get(0);
                    Map map = new HashMap();
                    map.put("id", dept.getDepartmentCode());
                    map.put("name", dept.getName());
                    map.put("code", dept.getDepartmentCode());
                    map.put("subnumber", dept.getChildMask());

                    DeptSafetyStaffBean dssb = mapper.deptStaff(dept.getDepartmentCode());
                    if (dssb == null) {
                        map.put("safetyStaffCode", null);
                        map.put("businessStaffCode", null);
                        map.put("safetyStaffName", null);
                        map.put("businessStaffName", null);
                        map.put("safetyLeader", null);
                        map.put("safetyLeaderName", null);
                        map.put("safetyOfficer", null);
                        map.put("safetyOfficerName", null);
                    } else {
                        map.put("safetyStaffCode", dssb.getSafetyStaffCode());
                        map.put("businessStaffCode", dssb.getBusinessStaffCode());
                        map.put("safetyStaffName", dssb.getSafetyStaffName());
                        map.put("businessStaffName", dssb.getBusinessStaffName());
                        map.put("safetyLeader", dssb.getSafetyLeader());
                        map.put("safetyLeaderName", dssb.getSafetyLeaderName());
                        map.put("safetyOfficer", dssb.getSafetyOfficer());
                        map.put("safetyOfficerName", dssb.getSafetyOfficerName());
                    }
                    map.put("isDept", 1);
                    map.put("addUser", null);
                    map.put("addUserName", null);
                    map.put("addTime", null);
                    map.put("updateUser", null);
                    map.put("updateUserName", null);
                    map.put("updateTime", null);
                    map.put("childList", new ArrayList<List<Map>>());
                    list.add(map);
                }
                return list;
            }

            if (deptList.size() > 1) {
                deptList = deptList.subList(1, deptList.size());
                for (DepartmentTreeBean deptBean : deptList) {
                    Map map = new HashMap();
                    map.put("id", deptBean.getDepartmentCode());
                    map.put("name", deptBean.getName());
                    map.put("code", deptBean.getDepartmentCode());

                    int subnumber = deptBean.getChildMask();
                    if (subnumber <= 0) {
                        subnumber = mapper.queryCountByPid(deptBean.getDepartmentCode());
                    }
                    map.put("subnumber", subnumber);

                    DeptSafetyStaffBean dssb = mapper.deptStaff(deptBean.getDepartmentCode());
                    if (dssb == null) {
                        map.put("safetyStaffCode", null);
                        map.put("businessStaffCode", null);
                        map.put("safetyStaffName", null);
                        map.put("businessStaffName", null);
                        map.put("safetyLeader", null);
                        map.put("safetyLeaderName", null);
                        map.put("safetyOfficer", null);
                        map.put("safetyOfficerName", null);
                    } else {
                        map.put("safetyStaffCode", dssb.getSafetyStaffCode());
                        map.put("businessStaffCode", dssb.getBusinessStaffCode());
                        map.put("safetyStaffName", dssb.getSafetyStaffName());
                        map.put("businessStaffName", dssb.getBusinessStaffName());
                        map.put("safetyLeader", dssb.getSafetyLeader());
                        map.put("safetyLeaderName", dssb.getSafetyLeaderName());
                        map.put("safetyOfficer", dssb.getSafetyOfficer());
                        map.put("safetyOfficerName", dssb.getSafetyOfficerName());
                    }
                    map.put("isDept", 1);
                    map.put("addUser", null);
                    map.put("addUserName", null);
                    map.put("addTime", null);
                    map.put("updateUser", null);
                    map.put("updateUserName", null);
                    map.put("updateTime", null);
                    map.put("childList", new ArrayList<List<Map>>());
                    list.add(map);
                }
            }
        }
        List<GridNode> gnList = mapper.queryByPid(id);
        for (GridNode node : gnList) {
            Map map = new HashMap();
            map.put("id", node.getId());
            map.put("name", node.getName());
            map.put("code", node.getCode());
            map.put("subnumber", node.getSubnumber());
            map.put("safetyStaffCode", node.getSafetyStaffCode());
            map.put("businessStaffCode", node.getBusinessStaffCode());
            map.put("safetyStaffName", node.getSafetyStaffName());
            map.put("businessStaffName", node.getBusinessStaffName());
            map.put("safetyLeader", node.getSafetyLeader());
            map.put("safetyLeaderName", node.getSafetyLeaderName());
            map.put("safetyOfficer", node.getSafetyOfficer());
            map.put("safetyOfficerName", node.getSafetyOfficerName());
            map.put("isDept", 0);
            map.put("addUser", node.getAddUser());
            map.put("addUserName", node.getAddUserName());
            map.put("addTime", node.getAddTime());
            map.put("updateUser", node.getUpdateUser());
            map.put("updateUserName", node.getUpdateUserName());
            map.put("updateTime", node.getUpdateTime());
            list.add(map);
        }
        return list;
    }

    @SuppressWarnings({"rawtypes", "deprecation"})
    @Override
    public MessageBean<?> list(String corpCode) {
        MessageBean<List> msg = MessageBean.create(0, "SUCCESS", List.class);
        if (StringUtils.isEmpty(corpCode)) {
            msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_SERVICE_EXCEPTION);
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            GridNodeMapper mapper = factory.getMapper(GridNodeMapper.class);
            msg.setData(mapper.queryByCorpCode(corpCode));
            factory.close();
        } catch (Exception e) {
            msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
            factory.close();
            return msg;
        }
        return msg;
    }

    @SuppressWarnings("deprecation")
    @Override
    public MessageBean<?> batchSave(StaffBean user, String corpCode, String nodeId, List<GridNode> beanList) {
        MessageBean<?> msg = MessageBean.create(0, "SUCCESS", void.class);
        if (StringUtils.isEmpty(nodeId) || beanList == null) {
            msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_SERVICE_EXCEPTION);
            return msg;
        }
        if (beanList.isEmpty()) {
            msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_SERVICE_EXCEPTION);
            return msg;
        }

        SessionFactory factory = new SessionFactory();
        try {
            GridNodeMapper mapper = factory.getMapper(GridNodeMapper.class);
            Map<String, String> map = new HashMap<>();
            for (GridNode gridNode : beanList) {
                //生成新id
                String id = DefaultIdGenerator.getInstance().generateLongId();
                map.put(gridNode.getId(), id);
                String pid = gridNode.getPid();
                if (StringUtils.isEmpty(pid)) {
                    gridNode.setPid(nodeId);
                } else {
                    gridNode.setPid(map.get(pid) == null ? nodeId : map.get(pid));
                }
                gridNode.setId(id);
                gridNode.setCode(Tools.getCode32());
                gridNode.setAddTime(new Date());
                gridNode.setAddUser(user.getCode());
                gridNode.setAddUserName(user.getName());
                gridNode.setCorpCode(corpCode);
                gridNode.setSubnumber(0);
                mapper.insert(gridNode);

                GridNode parent = mapper.queryById(gridNode.getPid());
                if (parent != null) {
                    //更新父级子节点数量
                    Integer subnumber = parent.getSubnumber();
                    subnumber++;
                    parent.setSubnumber(subnumber);
                    mapper.update(parent);
                }
            }
            factory.close();
            List<String> idList = beanList.stream().map(GridNode::getId).collect(Collectors.toList());
            singleThreadExecutor.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        refReshChildMap2(beanList.get(0).getPid(), idList, null);
                    } catch (Exception e) {
                        logger.error(e.getMessage(),e);
                    }
                }
            });

            return msg;
        } catch (Exception e) {
            msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
            factory.close(false);
            return msg;
        }
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext().getParent() == null) {//保证只执行一次
            List<CorpBean> list = corpManagementService.corpBeanList();  //已开通的公司
            Map<String, String> corpMap = corpManagementService.getCodeNameMap();
            SessionFactory factory = new SessionFactory();
            //只有一个水司
            String corpCode = "776B361BFFAC4F00BBF459CD1303A8B2";
            String corpName = "水之眼";
            Map<String, List<String>> map = new HashMap<String, List<String>>();
            Map<String, String> tempPositionMap = new HashMap<>();
            tempPositionMap.put(corpCode, corpName);
            List<Map> tempCorpNodeMapList = new ArrayList<>();//存储某个公司下所有的网格节点平铺结构
            List<Map> mapList = getChildList(factory, corpCode, 0);
            Map<String, List<Map>> tempDistrictMap = new HashMap<>();
            if (null != mapList && mapList.size() > 0) {
                tempCorpNodeMapList.add(mapList.get(0));
            }
            generateNodes2(corpCode, tempCorpNodeMapList, map, tempPositionMap, tempDistrictMap);
            childMap.put(corpCode, map);
            positionMap = tempPositionMap;
            corpNodesMap.put(corpCode, tempCorpNodeMapList);
            districtMap.put(corpCode, tempDistrictMap);
            corpMap.put(corpCode, corpName);
            factory.close();
//			for (CorpBean corp : list) {
//				//公司下所有子节点(包含网格)
//				List<String> idList = childAll(corp.getCorpCode(),new ArrayList<String>());
//				//网格id-子集列表
//				Map<String,List<String>> map = new HashMap<String,List<String>>();
//				Map<String,String> tempPositionMap=new HashMap<>();
//				tempPositionMap.put(corp.getCorpCode(),corp.getCorpName());
//				List<Map> tempCorpNodeMapList=new ArrayList<>();//存储某个公司下所有的网格节点平铺结构
//                List<Map> mapList=getChildList(factory,corp.getCorpCode(),0);
//                Map<String,List<Map>> tempDistrictMap=new HashMap<>();
//                if (null!=mapList&&mapList.size()>0){
//                    tempCorpNodeMapList.add(mapList.get(0));
//                }
//				generateNodes2(corp.getCorpCode(),tempCorpNodeMapList,map,tempPositionMap,tempDistrictMap);
////				map.put(corp.getCorpCode(), idList);
////				for (String id : idList) {
////					map.put(id, childAll(id,new ArrayList<String>()));
////					positionMap.put(id, getPosition(id, corp.getCorpCode(), new StringBuffer()));
////				}
////				//Map<String,Object> tree=genarateGridTree(corp.getCorpCode());
////				//treeMap.put(corp.getCorpCode(),tree);
//				childMap.put(corp.getCorpCode(), map);
//				positionMap=tempPositionMap;
//				corpNodesMap.put(corp.getCorpCode(),tempCorpNodeMapList);
//				districtMap.put(corp.getCorpCode(),tempDistrictMap);
//				corpMap.put(corp.getCorpCode(), corp.getCorpName());
//				factory.close();
//			}
        }
    }


    public List<String> childAll(String id, List<String> ret) {
        List<String> list = new ArrayList<>();
        if (null == list || list.size() <= 0)
            list = child(id);
        ret.addAll(list);
        for (String str : list) {
            childAll(str, ret);
        }
        return ret;
    }

    @SuppressWarnings({"deprecation", "unchecked"})
    public List<String> child(String id) {
        List<String> list = new ArrayList<String>();
        try (SessionFactory factory = new SessionFactory()) {
            MessageBean<?> deptMsg = util.depttree(id, 0);
            GridNodeMapper mapper = factory.getMapper(GridNodeMapper.class);
            if (deptMsg.getData() != null) {
                List<DepartmentTreeBean> deptList = (List<DepartmentTreeBean>) deptMsg.getData();
                if (deptList.size() > 0) {
                    deptList = deptList.subList(1, deptList.size());
                    for (DepartmentTreeBean deptBean : deptList) {
                        list.add(deptBean.getDepartmentCode());
                    }
                }
            }
            List<GridNode> gnList = mapper.queryByPid(id);
            for (GridNode node : gnList) {
                list.add(node.getId());
            }
        }
        return list;
    }

    @SuppressWarnings("deprecation")
    public String getPosition(String id, String corpCode, StringBuffer ret) {
        try (SessionFactory factory = new SessionFactory()) {
            GridNodeMapper mapper = factory.getMapper(GridNodeMapper.class);
            GridNode node = mapper.queryById(id);
            if (node != null) { //网格
                ret.insert(0, node.getName());
                ret.insert(0, "-");
                return getPosition(node.getPid(), corpCode, ret);
            }
            String deptPosition = getDeptPosition(id, corpCode);
            ret.insert(0, deptPosition);
            return ret.toString();
        }
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    private String getDeptPosition(String code, String corpCode) {
        if (positionMap.keySet().contains(code)) {
            return positionMap.get(code);
        }
        StringBuffer ret = new StringBuffer();
        MessageBean<?> msg = util.getParentDepts(code);
        if (msg.getCode() != 0) {
            return "";
        }
        List<DepartmentTreeBean> list = null;
        if (msg.getData() == null) {
            return "";
        }
        list = (List<DepartmentTreeBean>) msg.getData();
        if (list.isEmpty()) {
            return "";
        }
        ListIterator li = list.listIterator(list.size());
        while (li.hasPrevious()) {
            DepartmentTreeBean bean = (DepartmentTreeBean) li.previous();
            ret.insert(0, bean.getName());
            ret.insert(0, "-");
            if (corpCode.equals(bean.getDepartmentCode())) {
                ret.delete(0, 1);
                return ret.toString();
            }
        }
        ret.delete(0, 1);
        return ret.toString();
    }


    //当网格节点发生变化更新数据
    public synchronized void refReshChildMap(String corpCode) {
        List<String> idList = childAll(corpCode, new ArrayList<String>());
        //网格id-子集列表
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        map.put(corpCode, idList);
        for (String id : idList) {
            map.put(id, childAll(id, new ArrayList<String>()));
            positionMap.put(id, getPosition(id, corpCode, new StringBuffer()));
        }
        //treeMap.put(corpCode,genarateGridTree(corpCode));
        childMap.put(corpCode, map);
    }

    public synchronized void refReshChildMap2(String pid, List<String> insertIdList, String deleteId) {
        //只有一个水司
        String corpCode = "776B361BFFAC4F00BBF459CD1303A8B2";
        //获取指定code下的所有网格id集合(网格是id,部门是code)
        Map<String, List<String>> map = childMap.get("776B361BFFAC4F00BBF459CD1303A8B2");
        //获取父节点的下所有的子节点
        List<String> idList = map.get(pid);
        if (idList == null)
            idList = new ArrayList<>();
        if (null != insertIdList && insertIdList.size() > 0)
            idList.addAll(insertIdList);
        if (!StringUtils.isEmpty(deleteId))
            idList.remove(deleteId);
        map.put(pid, idList);
        childMap.put(corpCode, map);
    }

    public Map<String, String> getPositionMap() {
        return positionMap;
    }

    public Map<String, Map<String, List<String>>> getChildMap() {
        return childMap;
    }


    public MessageBean<?> getGridStaff(String code) {
        MessageBean<Map> msg = MessageBean.create(BusinessCode.MESSAGE_CODE_SUCCESS, BusinessCode.MESSAGE_DESCRIPTION_SUCCESS, Map.class);
        try (SessionFactory factory = new SessionFactory()) {
            GridNodeMapper mapper = factory.getMapper(GridNodeMapper.class);
            GridNode node = mapper.queryByCode(code);
            Map<String, String> map = new HashMap<>();
            if (node == null) {
                //是部门
                DeptSafetyStaff dss = mapper.queryDeptSafetyStaff(code);
                if (dss != null) {
                    map.put("code", code);
                    map.put("businessStaffCode", dss.getBusinessStaffCode());
                    map.put("safetyStaffCode", dss.getSafetyStaffCode());
                    map.put("businessStaffName", dss.getBusinessStaffName());
                    map.put("safetyStaffName", dss.getSafetyStaffName());
                    map.put("safetyLeader", dss.getSafetyLeader());
                    map.put("safetyLeaderName", dss.getSafetyLeaderName());
                    map.put("safetyOfficer", dss.getSafetyOfficer());
                    map.put("safetyOfficerName", dss.getSafetyOfficerName());
                    msg.setData(map);
                    return msg;
                } else {
                    map = gridStaff(code);
                    msg.setData(map);
                    return msg;
                }
            } else {
                //是网格
                if (!StringUtils.isEmpty(node.getBusinessStaffCode())) {
                    map.put("code", code);
                    map.put("businessStaffCode", node.getBusinessStaffCode());
                    map.put("safetyStaffCode", node.getSafetyStaffCode());
                    map.put("businessStaffName", node.getBusinessStaffName());
                    map.put("safetyStaffName", node.getSafetyStaffName());
                    map.put("safetyLeader", node.getSafetyLeader());
                    map.put("safetyLeaderName", node.getSafetyLeaderName());
                    map.put("safetyOfficer", node.getSafetyOfficer());
                    map.put("safetyOfficerName", node.getSafetyOfficerName());
                    msg.setData(map);
                    return msg;
                } else {
                    map = gridStaff(code);
                    msg.setData(map);
                    return msg;
                }
            }
        }
    }

    public MessageBean<?> appGetGridByName(String corpCode, String name) {
        MessageBean<List> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(corpCode)) {
                msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
                msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_SERVICE_EXCEPTION);
                return msg;
            }
            //判断corpCode是否为水司
            CorpBean bean = corpManagementService.getOne(corpCode).getData();
            if (null == bean) {
                msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
                msg.setDescription("不存在对应水司");
                return msg;
            }
            List<Map> list = new ArrayList<>();
            if (!StringUtils.isEmpty(name)) {
                Map<String, Map<String, List<String>>> map = getChildMap();
                if (!map.isEmpty()) {
                    String corp = "776B361BFFAC4F00BBF459CD1303A8B2";
                    Map<String, List<String>> corpGridMap = map.get(corp);
                    //获取该水司下所有网格的id和部门code集合
                    List<String> idList = corpGridMap.get(corpCode);
                    if (!idList.contains(corpCode)) {
                        idList.add(corpCode);
                    }
                    GridNodeMapper mapper = factory.getMapper(GridNodeMapper.class);
                    // 查询名称相似的网格
                    List<GridNode> nodeList = mapper.nodeListByIdListAndName(idList, name);
                    for (GridNode node : nodeList) {
                        Map gridMap = new HashMap();
                        generateGridMap(gridMap, node, mapper);
                        list.add(gridMap);
                    }
                    Map deptMap = (Map) util.getStaffAndDeptFuzzyQuery(name).getData();
                    List<DepartmentTreeBean> departmentTreeBeans = (List<DepartmentTreeBean>) deptMap.get("depts");
                    for (DepartmentTreeBean departmentTreeBean : departmentTreeBeans) {
                        if (idList.contains(departmentTreeBean.getDepartmentCode())) {
                            Map deptBeanMap = new HashMap();
                            generateDeptMap(deptBeanMap, departmentTreeBean, mapper);
                            list.add(deptBeanMap);
                        }

                    }
                }
            } else {
                if (!corpNodesMap.isEmpty()) {
                    list = corpNodesMap.get(corpCode);
                }
                if (null == list || list.size() <= 0) {
                    list = new ArrayList<>();
                    List<Map> mapList = getChildList(factory, corpCode, 0);
                    if (null != mapList && mapList.size() > 0) {
                        list.add(mapList.get(0));
                    }
                    generateNodes(corpCode, list);
                }
                msg.setData(list);
            }
            msg.setData(list);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
            return msg;
        }
    }

    //根据部门信息构建部门的map
    private Map generateDeptMap(Map map, DepartmentTreeBean deptBean, GridNodeMapper mapper) {
        map.put("id", deptBean.getDepartmentCode());
        map.put("name", deptBean.getName());
        map.put("code", deptBean.getDepartmentCode());

        int subnumber = deptBean.getChildMask();
        if (subnumber <= 0) {
            subnumber = mapper.queryCountByPid(deptBean.getDepartmentCode());
        }
        map.put("subnumber", subnumber);

        DeptSafetyStaffBean dssb = mapper.deptStaff(deptBean.getDepartmentCode());
        if (dssb == null) {
            map.put("safetyStaffCode", null);
            map.put("businessStaffCode", null);
            map.put("safetyStaffName", null);
            map.put("businessStaffName", null);
            map.put("safetyLeader", null);
            map.put("safetyLeaderName", null);
            map.put("safetyOfficer", null);
            map.put("safetyOfficerName", null);
        } else {
            map.put("safetyStaffCode", dssb.getSafetyStaffCode());
            map.put("businessStaffCode", dssb.getBusinessStaffCode());
            map.put("safetyStaffName", dssb.getSafetyStaffName());
            map.put("businessStaffName", dssb.getBusinessStaffName());
            map.put("safetyLeader", dssb.getSafetyLeader());
            map.put("safetyLeaderName", dssb.getSafetyLeaderName());
            map.put("safetyOfficer", dssb.getSafetyOfficer());
            map.put("safetyOfficerName", dssb.getSafetyOfficerName());
        }
        map.put("isDept", 1);
        map.put("addUser", null);
        map.put("addUserName", null);
        map.put("addTime", null);
        map.put("updateUser", null);
        map.put("updateUserName", null);
        map.put("updateTime", null);
        return map;
    }

    private Map generateGridMap(Map map, GridNode node, GridNodeMapper mapper) {
        map.put("id", node.getId());
        map.put("name", node.getName());
        map.put("code", node.getCode());
        map.put("subnumber", node.getSubnumber());
        map.put("safetyStaffCode", node.getSafetyStaffCode());
        map.put("businessStaffCode", node.getBusinessStaffCode());
        map.put("safetyStaffName", node.getSafetyStaffName());
        map.put("businessStaffName", node.getBusinessStaffName());
        map.put("safetyLeader", node.getSafetyLeader());
        map.put("safetyLeaderName", node.getSafetyLeaderName());
        map.put("safetyOfficer", node.getSafetyOfficer());
        map.put("safetyOfficerName", node.getSafetyOfficerName());
        map.put("isDept", 0);
        map.put("addUser", node.getAddUser());
        map.put("addUserName", node.getAddUserName());
        map.put("addTime", node.getAddTime());
        map.put("updateUser", node.getUpdateUser());
        map.put("updateUserName", node.getUpdateUserName());
        map.put("updateTime", node.getUpdateTime());
        return map;
    }

    @Override
    public MessageBean<Map> getAllNodes(String corpCode) {
        MessageBean<Map> msg = MessageBean.create(BusinessCode.MESSAGE_CODE_SUCCESS, BusinessCode.MESSAGE_DESCRIPTION_SUCCESS, Map.class);
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(corpCode)) {
                msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
                msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_SERVICE_EXCEPTION);
                return msg;
            }
            //判断corpCode是否为水司
            CorpBean bean = corpManagementService.getOne(corpCode).getData();
            if (null == bean) {
                msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
                msg.setDescription("不存在对应水司");
                return msg;
            }
            List<Map> list = new ArrayList<>();
            Map<String, List<String>> map = new HashMap<String, List<String>>();
            Map<String, String> map1 = new HashMap<>();
            List<Map> mapList = getChildList(factory, corpCode, 0);
            Map<String, Object> resultMap = new HashMap<>();
            if (null != mapList && mapList.size() > 0) {
                list.add(mapList.get(0));
                String name = (String) mapList.get(0).get("name");
                map1.put(corpCode, name);
                //generateNodes2(corpCode,list,map,map1);
                resultMap.put("positionMap", getPositionMap());
                resultMap.put("generatemap", map1);
            }
            //msg.setData(list);
            msg.setData(resultMap);
            return msg;
        }

    }

    @Override
    public List<String> getChildCodeList(String code) {
        List<String> list = new ArrayList<>();
        if (!StringUtils.isEmpty(code)) {
            list = childCodeListMap.get(code);
            if (list == null || list.size() <= 0) {
                list = new ArrayList<>();
                Map<String, List<String>> map = childMap.get("776B361BFFAC4F00BBF459CD1303A8B2");
                //获取指定code下的所有网格id集合(网格是id,部门是code)
                List<String> idList = map.get(code);
                if (idList != null && idList.size() > 0) {
                    //根据查询到id集合查询网格code
                    SessionFactory factory = new SessionFactory();
                    List<GridNode> nodeList = factory.getMapper(GridNodeMapper.class).nodeListByIdListAndName(idList, null);
                    List<String> nodeCodeList = nodeList.stream().map(GridNode::getCode).collect(Collectors.toList());
                    //实际的网格code
                    if (idList != null && idList.size() > 0)
                        list.addAll(idList);
                    if (nodeCodeList != null && nodeCodeList.size() > 0)
                        list.addAll(nodeCodeList);
                    childCodeListMap.put(code, list);
                    factory.close();
                }

            }
        }
        return list;
    }

    /**
     * 根据网格code获取所属单位
     *
     * @param gridCode 网格code
     * @return
     */
    @Override
    public DepartmentTreeBean getCorpInfo(SessionFactory factory, String gridCode) {
        // 查找当前网格是否为组织数据
        MessageBean<?> msg = util.depttree(gridCode, 0);
        GridNode node = null;
        if (msg.getCode() == 0 && null != msg.getData()) {
            // 是组织
            DepartmentTreeBean departmentTreeBean = null;
            List<DepartmentTreeBean> data = (List<DepartmentTreeBean>) msg.getData();
            if (null != data && data.size() > 0) {
                List<DepartmentTreeBean> collect = data.stream().filter(dept -> gridCode.equals(dept.getDepartmentCode())).collect(Collectors.toList());
                if (null != collect && collect.size() > 0) {
                    departmentTreeBean = collect.get(0);
                }
            }
            if (null != departmentTreeBean) {
                if (orgCode.equals(departmentTreeBean.getOrgCode())) {
                    msg = util.getParentDepts(departmentTreeBean.getDepartmentCode());
                    if (msg.getData() != null) {
                        List<DepartmentTreeBean> depTreeList = (List<DepartmentTreeBean>) msg.getData();
                        ListIterator li = depTreeList.listIterator(depTreeList.size());
                        while (li.hasPrevious()) {
                            DepartmentTreeBean bean = (DepartmentTreeBean) li.previous();
                            // 判断是否为单位
                            if ((bean.getDeptType() & 16) == 16) {
                                return bean;
                            }
                        }
                    }
                }
            }
        } else {
            // 是网格
            GridNodeMapper gridNodeMapper = factory.getMapper(GridNodeMapper.class);
            // 网格可能传的code，也可能传的id
            // 先根据code匹配，查不到再用id匹配
            node = gridNodeMapper.queryByCode(gridCode);
            if (null == node) {
                node = gridNodeMapper.queryById(gridCode);
            }
            if (null != node) {
                // 查找上级网格，直到查询到顶级网格为止
                GridNode parent = gridNodeMapper.queryById(node.getPid());
                while (null != parent) {
                    node = parent;
                    parent = gridNodeMapper.queryById(node.getPid());
                }
            }
        }
        // 为网格时，用查询到的顶级网格的父级id作为网格code查询
        if (null != node) {
            return getCorpInfo(factory, node.getPid());
        }
        return null;
    }

    private void generateNodes(String code, List<Map> list) {
        try (SessionFactory factory = new SessionFactory()) {
            List<Map> childList1 = getChildList(factory, code, 1);
            for (Map map : childList1) {
                String id = (String) map.get("id");
                Integer subnumber = (Integer) map.get("subnumber");
                if (subnumber == 0) {
                    //没有子节点了
                    list.add(map);
                } else {
                    list.add(map);
                    generateNodes(id, list);
                }
            }
        }
    }

    private void generateNodes2(String code, List<Map> list, Map<String, List<String>> childMap, Map<String, String> positionMap, Map<String, List<Map>> districtChidMap) {
        try (SessionFactory factory = new SessionFactory()) {
            List<Map> childList1 = getChildList(factory, code, 1);
            List<String> idList = childMap.get(code);
            String names = positionMap.get(code);
            if (null == idList)
                idList = new ArrayList<>();
            for (Map map : childList1) {
                StringBuilder sb = new StringBuilder();
                if (!StringUtils.isEmpty(names))
                    sb.append(names);
                String id = (String) map.get("id");
                String name = (String) map.get("name");
                Integer subnumber = (Integer) map.get("subnumber");
                sb.append("-");
                sb.append(name);
                positionMap.put(id, sb.toString());
                if (subnumber == 0) {
                    //没有子节点了
                    list.add(map);
                    List<String> tempList = new ArrayList<>();
                    //tempList.add(id);
                    childMap.put(id, tempList);
                } else {
                    list.add(map);
                    //idList.add(id);
                    generateNodes2(id, list, childMap, positionMap, districtChidMap);
                }
                List<String> tempList = childMap.get(id);
                if (null != tempList && tempList.size() > 0) {
                    idList.addAll(tempList);
                }
                idList.add(id);
            }
            districtChidMap.put(code, childList1);
            childMap.put(code, idList);
        }
    }

}
